import service from './axios'
import { ElMessage } from 'element-plus'


/**
 * 请求封装
 * @param {*} requestBody 请求时传过来的对象
 * @param {requestBody} method 请求方式
 * @param {requestBody} url 请求地址
 * @param {requestBody} showToast 请求报错时，是否显示提示
 * @param {requestBody} showLoading 是否显示loading
 * @param {requestBody} data 请求参数
 * @param {requestBody} headers 请求头
 * @returns 
 */
export default function request(requestBody) {
    const { url, data, headers = { 'content-type': 'application/json;charset=UTF-8' }, method, showToast = true, showLoading = true } = requestBody;
    return new Promise((resolve, reject) => {
        let requestData = {
            url,
            method,
            headers,
            data
        }, loadingKey;
        if (method === 'get' || method === 'delete') {
            requestData.params = data
            delete requestData.data
        }
        if (showLoading) {
            loadingKey = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })
        }
        service(requestData).then((res) => {
            showLoading && setTimeout(()=> {
                 loadingKey.close()
            }, 1000)
            if (res.code === 0) {
                resolve(res)
            } else if (res.code) {    // 请求返回失败时
                if (showToast) {
                    ElMessage.error(res.msg || res.message || '服务器开了个小差~')
                }
                reject(res);
            }else{
                resolve(res);
            }
        }).catch((err) => {
            showLoading && loadingKey.close()
            if(showToast) {
                ElMessage.error(res.msg || res.message || '服务器开了个小差~')
            }
            reject(err)
        })
    })
}